<?php
declare (strict_types = 1);

namespace app\admin\controller\erp;

use app\admin\controller\AuthController;
use app\admin\model\erp\ErpAccount;
use app\admin\model\erp\ErpSubjects;
use app\admin\model\system\SystemMenus;
use bbweb\services\UtilService as Util;
use think\facade\Config;
use think\Request;

class BasicsAccount extends AuthController
{
    /**
     * 显示列表
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function index(Request $req)
    {
        if ($req->isAjax()) {
            $data = [];
            $page = $req->param('page/d', 1);
            $limit = $req->param('limit/d', 15);
            $query = ErpAccount::order('id DESC');

            $data['count'] = $query->count('id');
            $data['data'] = $query->page($page,$limit)->select()->toArray();
            $data['code'] = 0;
            $data['msg'] = '';
            $types = Config::get('erp.account_type');
            foreach ($data['data'] as &$val) {
                $val['type_type'] = $types[$val['type']] ?? '--/--';
            }

            return json($data);
        }
        $sonAuth = SystemMenus::getSonAuth($req->controller(), $req->action(),array_keys($this->auth));

        // 显示页面
        $this->assign('sonAuth', $sonAuth);
        return $this->fetch();
    }

    /**
     * 创建资源.
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function add(Request $req)
    {
        if($req->isPost()) {
            $data = Util::postMore([
                ['name',''],
                ['account',''],
                ['type',0],
                ['bank_name',''],
                ['market',''],
                ['rate',0],
                ['money_limit',0],
            ], $req);
            if (!$data['name']) $this->error('请输入账户名称');
            if (!$data['account']) $this->error('请输入账号');
            $data['rate'] = round($data['rate'], 1);
            $data['money_limit'] = round($data['money_limit'], 4);
            $data['update_at'] = time();

            $sub = ErpSubjects::where('code', '=', '1002')->find();
            if(!$sub) $this->error('没有找到对应会计科目');
            $level = $sub['level'] + 1;
            $code = ErpSubjects::where('code','like', "{$sub['code']}%")->where('level',$level)->max('code');
            if($code <= $sub['code']) $code = $sub['code'] . '000';
            $code = $code + 1;
            $data['code'] = $code;

            ErpAccount::beginTrans();
            try {
                $res = ErpAccount::create($data);
                if($res && $res->id) {
                    $info = $res->toArray();
                    $item = [
                        'pid'       => $sub['id'],
                        'rel_id'    => $info['id'],
                        'rel_type'  => 'bank',
                        'code'      => $code,
                        'name'      => $info['name'],
                        'pname'     => $sub['pname'],
                        'level'     => $level,
                        'luck'      => 1,
                        'edit_luck' => 1,
                        'update_at' => time()
                    ];
                    $sb = ErpSubjects::create($item);
                    if(!$sb) {
                        throw new \think\Exception('对应会计科目写入失败！');
                    }
                } else {
                    throw new \think\Exception('保存失败！');
                }
                ErpAccount::commitTrans();
            } catch (\Exception $e) {
                ErpAccount::rollbackTrans();
                $this->error($e->getMessage());
            }
            $this->success('操作成功!');
        }
        $types = Config::get('erp.account_type');
        $this->assign('types',$types);
        return $this->fetch();
    }

    /**
     * 更新资源
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function edit(Request $req)
    {
        $id = intval($req->param('id/d'));
        if(!$id) $this->error('参数错误','', -1);
        $account = ErpAccount::where('id', $id)->find();
        if(!$account) $this->error('参数错误','', -1);
        if($req->isPost()) {
            $data = [];
            if($req->param('change/d')) {
                $data['status'] = $req->param('status/d');

                $data['update_at'] = time();
                $res = ErpAccount::where('id', $id)->update($data);
                if($res) {
                    $this->success('操作成功!');
                } else {
                    $this->error('操作失败');
                }
            } else {
                $data = Util::postMore([
                    ['name',''],
                    ['account',''],
                    ['type',0],
                    ['bank_name',''],
                    ['market',''],
                    ['rate',0],
                    ['money_limit',0],
                ], $req);
                if (!$data['name']) $this->error('请输入账户名称');
                if (!$data['account']) $this->error('请输入账号');
                $data['rate'] = round($data['rate'], 1);
                $data['money_limit'] = round($data['money_limit'], 4);
                $data['update_at'] = time();

                $sub = ErpSubjects::where('rel_id', '=', $id)->where('rel_type','=','bank')->find();
                if(!$sub) $this->error('没有对应会计科目');
                $sub_up = $account['name'] != $data['name'] ? true : false;
                ErpAccount::beginTrans();
                try {
                    $res = ErpAccount::where('id', $id)->update($data);
                    if($res) {
                        $item = [
                            'name'      => $data['name'],
                            'update_at' => time()
                        ];
                        if($sub_up) {
                            $sb = ErpSubjects::where('rel_id', $id)->where('rel_type','=','bank')->update($item);
                            if (!$sb) {
                                throw new \think\Exception('对应会计科目修改失败！');
                            }
                        }
                    } else {
                        throw new \think\Exception('保存失败！');
                    }
                    ErpAccount::commitTrans();
                } catch (\Exception $e) {
                    ErpAccount::rollbackTrans();
                    $this->error($e->getMessage());
                }
                $this->success('操作成功!');
            }
        }
        $types = Config::get('erp.account_type');
        $this->assign('types',$types);
        $this->assign('account', $account);
        return $this->fetch();
    }
}
